from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_meter
import master.utility as utility

class Meter(QDialog, Ui_meter.Ui_meterDlg):
  def __init__(self, dbConn, dataGlob,  parent=None):
        super(Meter, self).__init__(parent)
        self.setupUi(self)       
        self.initMenu()
        self.db = dbConn
        self.dataGlob = dataGlob
        self.util = utility.Utility(self.db)
        self.per_le.setText(self.util.getServerToday().date().toString("yyyy-MM"))
        
        self.mastModel = meterModel(self)
        self.mastModel.setTabel("mater_meteran")
        kol = ("no_meter","unit","l_awal","l_akhir","a_awal","a_akhir")
        self.mastModel.setKolom(kol)
#        self.mastModel.setHeaderData(0, Qt.Horizontal, QVariant("ID"))
#        self.mastModel.setHeaderData(1, Qt.Horizontal, QVariant("Business Unit"))
#        self.mastModel.setHeaderData(2, Qt.Horizontal, QVariant("Note"))
        
        self.master_tv.setModel(self.mastModel)
#        self.master_tv.setSelectionMode(QTableView.SingleSelection)
        self.master_tv.setSelectionBehavior(QTableView.SelectRows)        
        
  @pyqtSignature("")
  def on_per_le_editingFinished(self):
      if self.per_le.text() != "":
          self.per_cb.setCheckState(Qt.Checked)
      else:
          self.per_cb.setCheckState(Qt.Unchecked)
        
  def initMenu(self):
      self.retrieveAct = QAction(QIcon(":/retrieve.ico"), self.tr("Retrieve"), self)
#      self.retrieveAct.setShortcut ("Ctrl+R")
      self.connect(self.retrieveAct, SIGNAL("triggered()"), self.retrieveData)
      self.sortAct = QAction(QIcon(":/sort.ico"), self.tr("Sort"), self)
#      self.sortAct.setShortcut ("Ctrl+S")
      self.addAct = QAction(QIcon(":/add.ico"), self.tr("Add"), self)
#      self.addAct.setShortcut ("Ctrl+A")
      self.connect(self.addAct, SIGNAL("triggered()"), self.addData)
      self.editAct = QAction(QIcon(":/edit.ico"), self.tr("Edit"), self)
#      self.editAct.setShortcut ("Ctrl+E")
      self.connect(self.editAct, SIGNAL("triggered()"), self.editData)
      self.delAct = QAction(QIcon(":/del.ico"), self.tr("Delete"), self)
      self.connect(self.delAct, SIGNAL("triggered()"), self.delData)
#      self.delAct.setShortcut ("Ctrl+Del")
      self.printAct = QAction(QIcon("res/print.ico"), self.tr("Print Preview"), self)
#      self.printAct.setShortcut ("Ctrl+P")

  def retrieveData(self):
      qStr = "select no_meter, unit, l_awal, l_akhir, a_awal, a_akhir from mater_meteran"
#      filt = " no_meter like '"+self.per_le.text()+"%' and "
      filt = ""
      urut = " order by no_meter "
          
      if filt != "":
          filt = " where "+filt.left(len(filt)-4)
          
      qStr = qStr + filt + urut
      self.mastModel.setQuery(qStr, self.db)
      self.master_tv.setColumnWidth(0, 100)
      self.master_tv.setColumnWidth(1, 300)
      self.master_tv.setColumnWidth(2, 300)
      self.master_tv.resizeRowsToContents()
      self.mastModel.setQueryText(qStr)
      
  def addData(self):
      form = businessEdit.BusinessEdit(self.db, "add",  self.dataGlob, self)
      form.show()

  def editData(self):
      index = self.master_tv.currentIndex()
      if index.isValid():
          brs = self.mastModel.record(index.row())
          id = brs.value("kode_bu").toString()
          form = businessEdit.BusinessEdit(self.db, id,  self.dataGlob, self)
          form.show()

  def delData(self):
      index = self.master_tv.currentIndex()
      if index.isValid():
          brs = self.mastModel.record(index.row())
          id = brs.value("kode_bu").toString()
          nama = brs.value("nama_bu").toString()
          if QMessageBox.question(self, "Business Unit","Delete Data : "+nama+"?", QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes:
              qMast = QSqlQuery(self.db)
              self.db.transaction()
              qMast.exec_("delete from master_bisnis_unit where kode_bu = '"+id+"'")
              self.db.commit()
              self.retrieveData()

  def sortData(self):
       qStr = "select id_pelanggan, kode_pelanggan, nama, no_kartu, alamat1, kota1 from pelanggan"
       self.mastModel.setQuery(qStr, self.db)

  def printData(self):
       qStr = "select id_pelanggan, kode_pelanggan, nama, no_kartu, alamat1, kota1 from pelanggan"
       self.mastModel.setQuery(qStr, self.db)

  def contextMenuEvent(self, event):
        menu = QMenu(self)
        menu.addAction(self.retrieveAct)
        menu.addAction(self.sortAct)
        menu.addSeparator()
        menu.addAction(self.addAct)
        menu.addAction(self.editAct)
        menu.addSeparator()
        menu.addAction(self.delAct)
        menu.addSeparator()
        menu.addAction(self.printAct)
        menu.exec_(event.globalPos())

class meterModel(QSqlQueryModel):
    def __init__(self, parent=None):
        super(meterModel, self).__init__(parent)
        
    def flags(self, index):
        flags = QSqlQueryModel.flags(self, index)        
        if index.column() > 1:
            flags |= Qt.ItemIsEditable
        return flags
        
    def setTabel(self, tabel):
        self.tabel = tabel
        
    def setQueryText(self, qStr):
        self.qStr = qStr
        
    def setKolom(self, kolom):
        self.kolom = kolom
        
    def setData(self, index, value, role):
        if index.column() <= 1:
            return False        
        
        pk = QSqlQueryModel.index(self, index.row(), 0)
        id = self.data(pk)
        
        self.clear()
        
        query = QSqlQuery()
        query.prepare("update "+self.tabel+" set "+self.kolom[index.column()]+" = ? where no_meter = ?")
        query.addBindValue(QVariant(value.toString()))
        query.addBindValue(id)        
        hasil = query.exec_()  
        
        self.setQuery(self.qStr)
        return hasil
        
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = Meter()
    form.show()
    app.exec_()
